package com.mlm.mlmapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.ViewStub.OnInflateListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.CustomDialog;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.mlm.mlmapp.utils.PayResult;
import com.mlm.mlmapp.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.payment_order)
public class PaymentOrderActivity extends BaseActivity implements HTTPCons {
    AQuery aq;
    AjaxCallback<JSONObject> getPaymentInfoCB;
    List<RadioButton> radioGroup;

    @StringRes
    String money;
    @Pref
    Prefs_ pref;
    @Extra
    String orderid;
    @Extra
    String couponid;
    @ViewById
    LinearLayout items;
    @ViewById
    Button btn_price;
    @ViewById
    TextView btn_confirm;
    @ViewById
    LinearLayout pros;
    @ViewById
    Button btn_order_no;
    @ViewById
    RadioButton btn_alipay;
    @ViewById
    RadioButton btn_wechat;
    @ViewById
    ViewStub tipstub;
    String outtradeno;
    LayoutInflater inflater;
    @ColorRes
    int red;
    @ColorRes
    int blacktext;
    @ColorRes
    int greyborder;
    @ColorRes
    int lightgreytext;
    @DrawableRes
    Drawable red_edge_btn_long;
    private int total = 0;
    private static final int PAYMENT_TYPE_ALIPAY = 0;
    private static final int PAYMENT_TYPE_WECHAT = 1;
    private static final int PAYMENT_PAYING = 2;
    private static final int PAYMENT_SUCCESS = 3;
    private int payment_type;
    public static final String ORDER_REFRESH_FLAG = "com.mlm.mlmapp.order.refresh";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // 这一句必须的，否则Intent无法获得最新的数据
        this.orderid = intent.getStringExtra("orderid");
        getOrderInfo();
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
    }

    @AfterViews
    void init() {
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        inflater = LayoutInflater.from(this);
        radioGroup = new ArrayList<RadioButton>();
        radioGroup.add(btn_wechat);
        radioGroup.add(btn_alipay);

        btn_alipay.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    radioGroupChecked(buttonView);
                    payment_type = PAYMENT_TYPE_ALIPAY;
                }
            }
        });
        btn_wechat.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    radioGroupChecked(buttonView);
                    payment_type = PAYMENT_TYPE_WECHAT;
                }
            }
        });
        btn_wechat.setChecked(true);
        tipstub.setOnInflateListener(new OnInflateListener() {

            @Override
            public void onInflate(final ViewStub stub, View inflated) {
                // TODO Auto-generated method stub
                inflated.findViewById(R.id.close).setOnClickListener(
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                stub.setVisibility(View.GONE);
                            }
                        });
            }
        });
        tipstub.inflate();

        getPaymentInfoCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (status.getCode() != 200) {
                        Toast.makeText(aq.getContext(),
                                "网络异常:" + status.getCode(), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        try {
                            onSuccess(html);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        getOrderInfo();
    }


    void getAliPayOrderAction() {

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid));

        pairs.add(new BasicNameValuePair("type", "1"));

        CommonUtils.postRequest(obtion_alipay_order, aq,
                new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject obj,
                                         AjaxStatus status) {
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() == -103) {
                            Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            if (status.getCode() != 200) {
                                Toast.makeText(aq.getContext(),
                                        "网络异常:" + status.getCode(),
                                        Toast.LENGTH_SHORT).show();
                            } else {

                                try {
                                    if (obj.getBoolean("isSuccess")) {
                                        if ("1".equals(getJsonArray(obj, "errors").getString(0))) {
                                            Toast.makeText(aq.getContext(),
                                                    "支付成功！", Toast.LENGTH_SHORT)
                                                    .show();
//											PaymentActivity.this.finish();
                                            showAlertDialog();
                                        } else {

                                            JSONArray array = obj
                                                    .getJSONArray("errors");
                                            PaymentOrderActivity.this.outtradeno = getOutTradeNo(array.getString(0));
                                            pay(array.getString(0));
                                        }

                                    } else {
                                        Toast.makeText(aq.getContext(),
                                                obj.getString("errors"),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }, pairs);

    }

    String getOutTradeNo(String s) {
        String temp = null;
        if (s.length() > 1) {
            String[] arr = s.split("&");
            for (String st : arr) {
                if (st.contains("out_trade_no")) {
                    temp = st.substring(st.lastIndexOf("=") + 2, st.length() - 1);
                }
            }
        }

        return temp;
    }

    void getWechatPayOrderAction() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid));
        pairs.add(new BasicNameValuePair("type", "1"));

        CommonUtils.postRequest(obtion_wechatpay_order, aq,
                new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject obj,
                                         AjaxStatus status) {
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() == -103) {
                            Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            if (status.getCode() != 200) {
                                Toast.makeText(aq.getContext(),
                                        "网络异常:" + status.getCode(),
                                        Toast.LENGTH_SHORT).show();
                            } else {

                                try {
                                    if (obj.getBoolean("isSuccess")) {
                                        if ("1".equals(getJsonArray(obj, "errors").getString(0))) {
                                            Toast.makeText(aq.getContext(),
                                                    "支付成功！", Toast.LENGTH_SHORT)
                                                    .show();
//											PaymentActivity.this.finish();
                                            showAlertDialog();
                                        } else {
                                            wechatPay(new JSONObject(getJsonArray(obj, "errors").getString(0)));
                                            // pay(array.getString(0));
                                        }

                                    } else {
                                        Toast.makeText(aq.getContext(),
                                                obj.getString("errors"),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }, pairs);

    }


    /**
     * send sms authcode request
     *
     * @throws UnsupportedEncodingException
     */
    private void getOrderInfo() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid));
        CommonUtils
                .postRequest(get_payment_action, aq, getPaymentInfoCB, pairs);
    }


    private int couponcount;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    public void pay(final String payInfo) {
        /**
         * 完整的符合支付宝参数规范的订单信息
         */

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaymentOrderActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String payment_status = "";
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
//					Log.d("sort", "resultInfo" + resultInfo);
//					Log.d("sort", "resultStatus" + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        payment_status = WXPayEntryActivity.ALI_PAY_SUCCESS;
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            payment_status = WXPayEntryActivity.ALI_PAY_SUCCESS;
                        } else {
                            payment_status = WXPayEntryActivity.ALI_PAY_FAILURE;
                        }


                    }

                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(PaymentOrderActivity.this, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
            Intent intent = new Intent();
            intent.setAction(WXPayEntryActivity.PAY_FINISH);
            intent.putExtra("state", payment_status);
            PaymentOrderActivity.this.sendOrderedBroadcast(intent, null);
        }
    };

    private IWXAPI api;

    public void wechatPay(JSONObject json) {

        // String url =
        // "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";

        try {
            if (null != json && !json.has("retcode")) {
                PayReq req = new PayReq();
                // req.appId = "wxf8b4f85f3a794e77"; // 测试用appId

                req.appId = json.getString("appid");

                req.partnerId = json.getString("partnerid");
                req.prepayId = json.getString("prepayid");
                this.outtradeno = req.prepayId;
                req.nonceStr = json.getString("noncestr");
                req.timeStamp = json.getString("timestamp");
                req.packageValue = "Sign=WXPay";
                req.sign = json.getString("sign");
                req.extData = "app data"; // optional

                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

                IWXAPI wxApi = WXAPIFactory.createWXAPI(PaymentOrderActivity.this,
                        req.appId, true);
                wxApi.registerApp(req.appId);
                if (!wxApi.isWXAppInstalled()) {
                    Toast.makeText(PaymentOrderActivity.this, "没有安装微信",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!wxApi.isWXAppSupportAPI()) {
                    Toast.makeText(PaymentOrderActivity.this, "当前版本不支持支付功能",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                wxApi.sendReq(req);
            } else {
                Toast.makeText(PaymentOrderActivity.this,
                        "返回错误" + json.getString("retmsg"), Toast.LENGTH_SHORT)
                        .show();
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    void payNotify(String status) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid + ""));
        pairs.add(new BasicNameValuePair("outTradeNo", this.outtradeno));
        pairs.add(new BasicNameValuePair("payStatus", status));
        String url;

        CommonUtils.postRequest(alipay_notify, aq,
                new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject obj,
                                         AjaxStatus status) {
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() == -103) {
                            Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            if (status.getCode() != 200) {
                                Toast.makeText(aq.getContext(),
                                        "网络异常:" + status.getCode(),
                                        Toast.LENGTH_SHORT).show();
                            } else {

                                try {
                                    if (obj.getBoolean("isSuccess")) {


                                    } else {
                                        Toast.makeText(aq.getContext(),
                                                obj.getString("errors"),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }, pairs);
    }
    //
    // /**
    // * check whether the device has authentication alipay account.
    // * 查询终端设备是否存在支付宝认证账户
    // *
    // */
    // public void check(View v) {
    // Runnable checkRunnable = new Runnable() {
    // @Override
    // public void run() {
    // // 构造PayTask 对象
    // PayTask payTask = new PayTask(PaymentActivity.this);
    // // 调用查询接口，获取查询结果
    // boolean isExist = payTask.checkAccountIfExist();
    //
    // Message msg = new Message();
    // msg.what = SDK_CHECK_FLAG;
    // msg.obj = isExist;
    // mHandler.sendMessage(msg);
    // }
    // };
    //
    // Thread checkThread = new Thread(checkRunnable);
    // checkThread.start();
    //
    // }

    // /**
    // * get the sdk version. 获取SDK版本号
    // *
    // */
    // public void getSDKVersion() {
    // PayTask payTask = new PayTask(this);
    // String version = payTask.getVersion();
    // Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    // }

    void onSuccess(JSONObject obj) throws JSONException {
        int realMoney = getJsonInt(obj, "realMoney");
        int payMoney = getJsonInt(obj, "payMoney");
        if ("5".equals(getJsonString(obj, "status"))) {
            btn_price.setText(getString(R.string.money, realMoney - payMoney));
        } else {
            btn_price.setText(getString(R.string.money, payMoney));
        }
        btn_order_no.setText(getJsonString(obj, "orderNumb"));
    }

    @Click
    void btn_confirm() {
        // getPayOrderAction();
        if (payment_type == PAYMENT_TYPE_ALIPAY) {
            getAliPayOrderAction();
        } else {
            getWechatPayOrderAction();
        }
//		btn_confirm.setEnabled(false);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!btn_confirm.isEnabled()) {

        }

        btn_confirm.setEnabled(true);

    }

    @Receiver(actions = WXPayEntryActivity.PAY_FINISH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onPayFinish(Intent intent) {
        String state = intent.getStringExtra("state");
        if (state != null) {

            if (state.equals(WXPayEntryActivity.ALI_PAY_SUCCESS) || state.equals(WXPayEntryActivity.WECHAT_PAY_SUCCESS)) {
                Toast.makeText(this, "支付成功",
                        Toast.LENGTH_SHORT).show();
                CommonUtils.sendBroadCast(this, CollectionsActivity.COLLECTION_REFRESH, "refreshflag", "0");

                showAlertDialog();
                payNotify("3");
            } else {
                payNotify("20");
                Toast.makeText(this, "支付失败",
                        Toast.LENGTH_SHORT).show();
            }
            Intent bc = new Intent();
            bc.setAction(ORDER_REFRESH_FLAG);
            bc.putExtra("refreshflag", "0");
            this.sendOrderedBroadcast(bc, null);
        }


    }

    private void radioGroupChecked(CompoundButton buttonView) {
        for (RadioButton rb : radioGroup) {
            if (rb != buttonView) {
                rb.setChecked(false);
            }

        }
    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
//		super.onBackPressed();
        PaymentWaitActivity_.intent(this).extra("orderid", orderid).start();
        this.finish();
    }

    public void showAlertDialog() {

        CustomDialog.Builder builder = new CustomDialog.Builder(this);

        builder.setPositiveButton("返回首页", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                MainActivity_.intent(PaymentOrderActivity.this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
                dialog.dismiss();
                PaymentOrderActivity.this.finish();

                //设置你的操作事项
            }
        });

        builder.setNegativeButton("查看订单",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        OrdersActivity_.intent(PaymentOrderActivity.this).extra("flag", OrdersActivity.TYPE_BOOKED).start();

                        // TODO: 2016/3/10
						Intent intent = new Intent();
						intent.setAction(ORDER_REFRESH_FLAG);
						intent.putExtra("refreshflag", "0");
						getBaseContext().sendOrderedBroadcast(intent, null);
                        dialog.dismiss();
                        PaymentOrderActivity.this.finish();
                    }
                });

        builder.create().show();

    }
}
